#include <stdio.h>
#include "parsing.h"
#include "strings.h"


void http_header_read_line(char * buffer) 
{
  fgets(buffer, MAX_HEADER_LINE_LENGTH, stdin);
  strip_newlines(buffer);
}

void analize_token(char * name, char * value, struct fileupload_http_header_t * header) 
{
  value = strip_quotes(value);
  if (strcmp(name, "name") == 0) {
    strcpy(header->name, value);
  } else if (strcmp(name, "filename") == 0) {
    strcpy(header->file_name, value);
  }
}


void parse_token(char * token, struct fileupload_http_header_t * header) 
{
  token = trim(token);
  char * value = strchr(token, '=');
  if (value) {
    *value = 0;
    value++;
    analize_token(token, value, header);
  }
}

void parse_content_disposition(char * line, struct fileupload_http_header_t * header)
{
  int max_tokens = 10;
  int max_token_length = 100;
  char * * tokens = init_tokens(max_tokens, max_token_length);
  
  split(line, ';', tokens); 
  int i = 0;
  for (i = 0; tokens[i] != 0; i++) {
    parse_token(tokens[i], header);
  }
  free_tokens(tokens, max_tokens); 
}

void http_header_parse_line(char * line, struct fileupload_http_header_t * header) 
{
  strip_newlines(line);
  char * pos = strchr(line, ':');
  if (pos != 0) {
    *pos = 0;
    if (strcmp(line, "Content-Type") == 0) {
      pos++;
      pos = trim(pos);
      strncpy(header->content_type, pos, MAX_HEADER_LINE_LENGTH);
    }
    else if (strcmp(line, "Content-Disposition") == 0) {
      parse_content_disposition(pos+2, header);
    }
  }
}


void http_header_parse(struct fileupload_http_header_t * header)
{
  char buffer[MAX_HEADER_LINE_LENGTH];
  fgets(header->mime_separator, MAX_HEADER_LINE_LENGTH, stdin);

  do {
    http_header_read_line(buffer);
    if (strcmp(buffer, "") != 0)
      http_header_parse_line(buffer, header);
  } while (strcmp(buffer, "") != 0); 
}

#define PRINT_FIELD(struct_name, field) printf(#field ": {%s}<br/>\n", struct_name->field);
void http_header_dump(struct fileupload_http_header_t * header)
{
  PRINT_FIELD(header, name);
  PRINT_FIELD(header, file_name);
  PRINT_FIELD(header, content_type);
  PRINT_FIELD(header, mime_separator);
}
#undef PRINT_FIELD

